<template>
    <view class="container">
        <input type="text" @input="onkeyinput" class="search" value="" placeholder="搜素内容" />
        <!-- <button type="default" @click="searchPosition">点击</button> -->
        <!-- <button type="default" @click="searchPosition" class="btn">搜索</button> -->
        <text @click="searchPosition" class="btn">搜索</text>
        <map
            class="map"
            @regionchange="regionchangeevent"
            @callouttap="callouttapevent"
            @anchorpointtap="anchorpointtap"
            scale="14"
            :latitude="latitude"
            :longitude="longitude"
            :markers="covers"
            @markertap="markertap"
            @tap="maptap"
        ></map>
        <wyb-popup ref="popup" type="bottom" height="130" width="500" radius="6" zIndex="9999999" :showCloseIcon="true">
            <view class="popup-content">
                <navigator :url="'../../pages/map/charging/charging?markerId=' + markerId" open-type="navigate">
                    <view class="title">{{ powerOneData.powerplanName }}</view>
                </navigator>

                <view class="title-msg">
                    <text>对外开放</text>
                    <text>停车收费</text>
                    <text>互联互通</text>
                </view>
                <view class="title-price">
                    <view class="left">
                        <text>{{ powerOneData.stationPrice }}</text>
                        <text>元/度</text>
                    </view>
                    <view class="right" @click="toMapAPP(latitude, longitude, name)">
                        <image class="image" src="../../static/map/daozhequ@2x.png" mode=""></image>
                        <text>到这去</text>
                    </view>
                </view>
            </view>
        </wyb-popup>
    </view>
</template>

<script>
// （1）引入SDK
import QQMapWX from '../../utils/qqmap-wx-jssdk.min.js';
let qqmapsdk;
import { createNamespacedHelpers } from 'vuex';
const { mapState, mapMutations, mapActions } = createNamespacedHelpers('map');
export default {
    data() {
        return {
            id: 0, // 使用 marker点击事件 需要填写id
            title: 'map',
            latitude: 39.909,
            longitude: 116.39742,
            currentLatitude: '',
            currentLongitude: '',
            covers: [],
            searchData: '酒店',
            name: '',
            markerId: null
        };
    },
    computed: {
        ...mapState(['powerData', 'powerOneData'])
    },
    methods: {
        maptap(e){
            console.log('tap',e);
        },
        ...mapActions(['getridge', 'getOnePowerData']),
        //打开第三方地图
        toMapAPP(latitude, longitude, name) {
            console.log(latitude, longitude, name);
            this.$refs.popup.hide();
            let url = '';
            if (plus.os.name == 'Android') {
                //判断是安卓端
                plus.nativeUI.actionSheet(
                    {
                        //选择菜单
                        title: '选择地图应用',
                        cancel: '取消',
                        buttons: [{ title: '腾讯地图' }, { title: '百度地图' }, { title: '高德地图' }]
                    },
                    function(e) {
                        switch (e.index) {
                            //下面是拼接url,不同系统以及不同地图都有不同的拼接字段
                            case 1:
                                //注意referer=xxx的xxx替换成你在腾讯地图开发平台申请的key
                                url = `qqmap://map/geocoder?coord=${latitude},${longitude}&referer=UCNBZ-4MOEX-XPN4L-ZRKTA-NHKVS-EVBDB`;
                                break;
                            case 2:
                                url = `baidumap://map/marker?location=${latitude},${longitude}&title=${name}&coord_type=gcj02&src=andr.baidu.openAPIdemo`;
                                break;
                            case 3:
                                url = `androidamap://viewMap?sourceApplication=appname&poiname=${name}&lat=${latitude}&lon=${longitude}&dev=0`;
                                break;
                            default:
                                break;
                        }
                        if (url != '') {
                            url = encodeURI(url);
                            //plus.runtime.openURL(url,function(e){})调起手机APP应用
                            plus.runtime.openURL(url, function(e) {
                                plus.nativeUI.alert('本机未安装指定的地图应用');
                            });
                        }
                    }
                );
            } else {
                // iOS上获取本机是否安装了百度高德地图，需要在manifest里配置
                // 在manifest.json文件app-plus->distribute->apple->urlschemewhitelist节点下添加
                //（如urlschemewhitelist:["iosamap","baidumap"]）
                plus.nativeUI.actionSheet(
                    {
                        title: '选择地图应用',
                        cancel: '取消',
                        buttons: [{ title: '腾讯地图' }, { title: '百度地图' }, { title: '高德地图' }]
                    },
                    function(e) {
                        switch (e.index) {
                            case 1:
                                url = `qqmap://map/geocoder?coord=${latitude},${longitude}&referer=xxx`;
                                break;
                            case 2:
                                url = `baidumap://map/marker?location=${latitude},${longitude}&title=${name}&content=${name}&src=ios.baidu.openAPIdemo&coord_type=gcj02`;
                                break;
                            case 3:
                                url = `iosamap://viewMap?sourceApplication=applicationName&poiname=${name}&lat=${latitude}&lon=${longitude}&dev=0`;
                                break;
                            default:
                                break;
                        }
                        if (url != '') {
                            url = encodeURI(url);
                            plus.runtime.openURL(url, function(e) {
                                plus.nativeUI.alert('本机未安装指定的地图应用');
                            });
                        }
                    }
                );
            }
        },
        //
        onkeyinput(e) {
            this.searchData = e.target.value;
        },
        getCurrentPositon() {
            uni.getLocation({
                success: res => {
                    const { longitude, latitude } = res;
                    this.latitude = latitude;
                    this.longitude = longitude;
                    // console.log('getCurrentPositon', latitude, longitude);
                    this.currentLatitude = latitude;
                    this.currentLongitude = longitude;
                    // this.covers = [...this.powerData, ...this.covers];
                    // this.covers.forEach((item, index) => {
                    //     this.covers[index] = {
                    //         id: item.powerplantId,
                    //         latitude: item.powerplantCoordinate.latitude,
                    //         longitude: item.powerplantCoordinate.longitude,
                    //         iconPath: '../../static/map/position3.png',
                    //         width: 30,
                    //         height: 30,
                    //         callout: {
                    //             content: '地址为:' + item.powerplantAddress,
                    //             display: 'BYCLICK',
                    //             padding: 10
                    //         }
                    //     };
                    // });
                    this.covers[0] = {
                        latitude: this.latitude,
                        longitude: this.longitude,
                        iconPath: '../../static/map/position3.png',
                        width: 30,
                        height: 30,
                        callout: {
                            content: '地址为:' + '成都',
                            display: 'BYCLICK',
                            padding: 10
                        }
                    };
                }
            });
        },
        callouttapevent(e) {
            console.log(333333,e);
            this.$refs.popup.show();
            // let info = uni.createSelectorQuery().select(".map");
            // 	info.boundingClientRect(function(data) {
            //     console.log(data);
            // }).exec()
            uni.switchTab({
                url:"/pages/home/home"
            })
        },
        markertap(e) {
            console.log('markertap',e);
            let { markerId } = e.detail;
            this.markerId = markerId;
            this.getOnePowerData(markerId);
        },
        // 点击定位标时触发
        anchorpointtap(e) {
            console.log('anchorpointtap',e);
            let { latitude, longitude, name } = e.detail;
            this.latitude = latitude;
            this.longitude = longitude;
            this.name = name;
        },
        // 视野发生变化时触发
        regionchangeevent(e) {
            console.log(e);
            // 拖动结束
            if (e.type == 'end') {
                const { longitude, latitude } = e.target.centerLocation;
                // console.log(longitude, latitude);
                // 拖动结束后，不要直接把经度纬度赋值latitude
                this.currentLatitude = latitude;
                this.currentLongitude = longitude;
            }
        },
        // 点击搜索按钮，执行指定内容搜索
        searchPosition() {
            this.getridge({ lat: this.latitude, lng: this.longitude });
            // let _this = this;
            // 调用接口
            // const location = this.currentLatitude + ',' + this.currentLongitude;
            setTimeout(() => {
                this.covers = this.powerData;
                this.covers.forEach((item, index) => {
                    this.covers[index] = {
                        // 获取返回结果，放到mks数组中
                        marker: item.content.powerplantId,
                        latitude: item.content.location.lat,
                        longitude: item.content.location.lon,
                        iconPath: '../../static/map/position3.png', //图标路径
                        width: 30,
                        height: 30,
                        callout: {
                            content: '地址为:' + item.content.powerplantAddress,
                            display: 'BYCLICK',
                            padding: 10
                        }
                    };
                });
            }, 2000);
            // qqmapsdk.search({
            //     // 关进词语
            //     keyword: this.searchData,
            //     // 位置信息，以你当前地图的中心位置作为搜索的点
            //     location: location,
            //     success: function(res) {
            //         let mks = [];
            //         for (var i = 0; i < res.data.length; i++) {
            //             mks.push({
            //                 // 获取返回结果，放到mks数组中
            //                 title: res.data[i].title,
            //                 id: res.data[i].id,
            //                 latitude: res.data[i].location.lat,
            //                 longitude: res.data[i].location.lng,
            //                 iconPath: '../../static/map/position2.png', //图标路径
            //                 width: 20,
            //                 height: 20,
            //                 callout: {
            //                     content: '地址为:' + res.data[i].address,
            //                     display: 'BYCLICK',
            //                     padding: 10
            //                 }
            //             });
            //         }
            //         console.log(res);
            //         _this.covers = mks;
            //     },
            //     fail: function(error) {
            //         console.log(error);
            //     }
            // });
        }
    },
    created: function() {
        // 实例化API核心类
        qqmapsdk = new QQMapWX({
            key: 'UCNBZ-4MOEX-XPN4L-ZRKTA-NHKVS-EVBDB'
        });
        this.getCurrentPositon();
    }
};
</script>

<style lang="scss" scoped>
.container {
    position: relative;
    .map {
        width: 100%;
        height: 60vh;
    }
    .search {
        width: 98%;
        height: 6vh;
        margin-top: 1%;
        margin-left: 1%;
        background-color: white;
    }

    .btn {
        position: absolute;
        right: 1%;
        top: 0%;
        z-index: 10000;
        height: 6vh;
        line-height: 6vh;
        right: 40rpx;
    }
    .popup-content {
        padding: 40rpx 24rpx 40rpx 24rpx;
        .title {
            font-size: 32rpx;
            color: #333333;
            font-weight: 600;
        }
        .title-msg {
            margin-top: 8rpx;
            text {
                display: inline-block;
                width: 100rpx;
                height: 40rpx;
                background-color: #f5e1be;
                color: #ffa85e;
                font-size: 18rpx;
                border-radius: 14rpx;
                margin-right: 8rpx;
                text-align: center;
                line-height: 40rpx;
            }
        }
        .title-price {
            display: flex;
            justify-content: space-between;
            margin-top: 34rpx;
            .left {
                text:nth-child(1) {
                    font-size: 40rpx;
                    color: #ff5300;
                    font-weight: 600;
                }
                text:nth-child(2) {
                    font-size: 20rpx;
                    color: #333333;
                }
            }
            .right {
                width: 160rpx;
                height: 60rpx;
                background-color: #ff6208;
                border-radius: 36rpx;
                display: flex;
                justify-content: center;
                align-items: center;
                .image {
                    width: 20rpx;
                    height: 30rpx;
                }
                text {
                    font-size: 24rpx;
                    color: #ffffff;
                    margin-left: 8rpx;
                }
            }
        }
    }
}
</style>
